<template>
  <div class="role-add-update-component">
    <el-dialog
      v-if="modelValue.visible"
      v-model="modelValue.visible"
      :title="
        !modelValue.form.id
          ? `新增${modelValue.title}`
          : `修改${modelValue.title}`
      "
      width="700px"
    >
      <div style="padding-right: 50px">
        <el-form
          :model="modelValue.form"
          :rules="modelValue.rules"
          ref="addEditRef"
          :label-width="80"
        >
          <el-form-item label="角色名" prop="name">
            <el-input
              v-model="modelValue.form.name"
              autocomplete="off"
              placeholder="请输入角色名"
              :disabled="modelValue.form.disabled"
            />
          </el-form-item>
          <el-table
            :data="modelValue.permissionList"
            border
            stripe
            style="width: 100%"
          >
            <el-table-column label="权限描述" width="160">
              <template #default="{ row }">
                <div class="child-item">
                  <el-checkbox
                    v-model="row.selected"
                    @change="handleLeftCheck(row)"
                  ></el-checkbox>
                  <span>{{ row.permissionName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="权限动作">
              <template #header>
                <div
                  class="table-header-item"
                  style="display: flex; align-items: center"
                >
                  <span style="margin-right: 20px">权限动作</span>
                  <div style="display: flex; align-items: center">
                    <el-checkbox
                      v-model="modelValue.allPermissionSelected"
                      @change="handleAllCheck()"
                    ></el-checkbox>
                    <span style="margin-left: 5px">全选</span>
                  </div>
                </div>
              </template>
              <template #default="{ row }">
                <div
                  class="table-right"
                  v-if="row.children && row.children.length"
                >
                  <div
                    class="child-item"
                    v-for="childRow in row.children"
                    :key="childRow.id"
                  >
                    <el-checkbox
                      @change="handleRightCheck(row)"
                      v-model="childRow.selected"
                    ></el-checkbox>
                    <span>{{ childRow.permissionName }}</span>
                  </div>
                </div>
                <div class="child-item" v-else>
                  <el-checkbox
                    @change="handleLeftCheck(row)"
                    v-model="row.selected"
                  ></el-checkbox>
                  <span>{{ row.permissionName }}</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="ensure"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { addRole, updateRole } from '@/api/ums-user.api'

const props = defineProps(['modelValue'])
const addEditRef = ref<FormInstance>()

/***
 * 确认弹框
 */
const ensure = () => {
  startAddRole()
}

/***
 * 取消弹框
 */
const cancel = () => {
  props.modelValue.visible = false
}

const handleLeftCheck = (item: any) => {
  if (item.children && item.children.length > 0) {
    for (let i = 0; i < item.children.length; i++) {
      let row = item.children[i]
      row.selected = item.selected
    }
  }
  isAllSelected()
}

const handleRightCheck = (item: any) => {
  if (!item.children || item.children.length === 0) return
  let childNoSelectedList = item.children.filter((row) => !row.selected)
  item.selected = !childNoSelectedList.length
  isAllSelected()
}

const isAllSelected = () => {
  let permissionValueList = props.modelValue.permissionList || []
  for (let item of permissionValueList) {
    if (!(item as any).selected) {
      props.modelValue.allPermissionSelected = false
      return
    }
    if ((item as any).children) {
      let children = (item as any).children || []
      for (let child of children) {
        if (!child.selected) {
          props.modelValue.allPermissionSelected = false
          return
        }
      }
    }
  }
  props.modelValue.allPermissionSelected = true
}

const handleAllCheck = () => {
  let permissionValues = props.modelValue.permissionList
  permissionValues.map((item: any) => {
    item.selected = props.modelValue.allPermissionSelected
    if (item.children && item.children.length > 0) {
      for (let i = 0; i < item.children.length; i++) {
        let row = item.children[i]
        row.selected = props.modelValue.allPermissionSelected
      }
    }
    return item
  })
}

const startAddRole = () => {
  let formData = {
    name: props.modelValue.form.name,
    permissionIdList: [],
  }

  //增加权限
  let permissionList = props.modelValue.permissionList
  permissionList.forEach((item: any) => {
    if (item.selected) {
      formData.permissionIdList.push(item.id)
    }
    if (item.children) {
      item.children.forEach((child: any) => {
        if (child.selected) {
          formData.permissionIdList.push(child.id)
        }
      })
    }
  })

  if (!addEditRef.value) return
  addEditRef.value.validate((valid, fields) => {
    if (valid) {
      if (props.modelValue.form.id) {
        updateRole({
          ...formData,
          id: props.modelValue.form.id,
        })
          .then((res) => {
            cancel()
            ElMessage({
              message: props.modelValue.title + '修改成功',
              type: 'success',
            })

            if (props.modelValue.refreshDataList) {
              props.modelValue.refreshDataList()
            }
          })
          .catch((err) => {
            ElMessage({
              message: err.msg || err,
              type: 'error',
            })
          })
        return
      }

      addRole(formData)
        .then((res) => {
          cancel()
          ElMessage({
            message: props.modelValue.title + '新增成功',
            type: 'success',
          })
          if (props.modelValue.refreshDataList) {
            props.modelValue.refreshDataList()
          }
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: 'error',
          })
        })
    }
  })
}
</script>
<style lang="scss" scoped>
.table-left {
  display: flex;
  align-items: center;
  text-align: left;
}
.table-right {
  display: flex;
  align-items: center;
  text-align: left;
  flex-wrap: wrap;
}

.child-item {
  margin-right: 20px;
  display: flex;
  align-items: center;
  span {
    margin-left: 5px;
  }
}
</style>
